package com.th.basemodel.utils

import android.app.Activity
import android.content.Context
import android.view.View
import android.view.inputmethod.InputMethodManager

object KeyboardUtils {

    /**
     * 显示软键盘
     * @param activity 当前Activity
     * @param view 需要获取焦点的View，如果为null则尝试获取当前焦点View
     */
    fun showKeyboard(activity: Activity, view: View? = null) {
        val inputMethodManager = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        val targetView = view ?: activity.currentFocus ?: View(activity)
        inputMethodManager.showSoftInput(targetView, InputMethodManager.SHOW_IMPLICIT)
    }

    /**
     * 隐藏软键盘
     * @param activity 当前Activity
     */
    fun hideKeyboard(activity: Activity) {
        val view = activity.currentFocus ?: View(activity)
        val inputMethodManager = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0)
    }

    /**
     * 切换软键盘状态
     * @param activity 当前Activity
     */
    fun toggleKeyboard(activity: Activity) {
        val inputMethodManager = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)
    }

    /**
     * 强制显示软键盘（即使没有焦点View）
     * @param activity 当前Activity
     */
    fun forceShowKeyboard(activity: Activity) {
        val inputMethodManager = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY)
    }
}